package com.hospital.dictionary.module.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hospital.common.core.result.ErrorTip;
import com.hospital.common.core.result.SuccessTip;
import com.hospital.common.core.result.Tip;
import com.hospital.common.core.utils.RedisUtils;
import com.hospital.dictionary.module.controller.base.BaseController;
import com.hospital.dictionary.module.controller.dto.LoginDto;
import com.hospital.dictionary.module.controller.dto.UserDto;
import com.hospital.dictionary.module.entity.StaffDict;
import com.hospital.dictionary.module.entity.SysUserRole;
import com.hospital.dictionary.module.service.StaffDictService;
import com.hospital.dictionary.module.service.SysUserRoleService;
import com.hospital.dictionary.utils.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lvyao
 * @since 2022-02-14
 */
@RestController
@RequestMapping("/module/staffDict")
public class StaffDictController extends BaseController<StaffDict, StaffDictService> {

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    public Tip createDo(@RequestBody StaffDict object) {
        super.createDo(object);
        if(oConvertUtils.isNotEmpty(object.getSelectedroles())) {
            String[] arr = object.getSelectedroles().split(",");
            for (String roleId : arr) {
                SysUserRole userRole = new SysUserRole();
                userRole.setRoleId(roleId);
                userRole.setUserId(object.getStaffNo());
                sysUserRoleService.save(userRole);
            }
        }
        return new SuccessTip("操作成功");
    }

    @Override
    public Tip updateDto(@RequestBody StaffDict object) {
        if(oConvertUtils.isNotEmpty(object.getSelectedroles())) {
            boolean remove = sysUserRoleService.remove(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, object.getEmpNo()));
            String[] arr = object.getSelectedroles().split(",");
            for (String roleId : arr) {
                SysUserRole userRole = new SysUserRole();
                userRole.setRoleId(roleId);
                userRole.setUserId(object.getStaffNo());
                sysUserRoleService.save(userRole);
            }
        }
        return super.updateDto(object);
    }

    @PostMapping("/login")
    public Tip login(HttpServletRequest request, @RequestBody UserDto user){
        QueryWrapper<StaffDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("staff_no",user.getUsername()).eq("cm_password",user.getPassword());
        StaffDict one=baseService.getOne(queryWrapper);
        if(one!=null){
            String uuid= IdWorker.get32UUID();
            boolean setResult= RedisUtils.setValEx(uuid, JSON.toJSONString(one),7200);
            if(setResult) {
                LoginDto loginDto = new LoginDto(uuid, one);
                return new SuccessTip(loginDto);
            }else {
                return new ErrorTip(302,"redis设置失败");
            }
        }
        return new ErrorTip(303,"用户信息不存在");
    }

    @GetMapping("/userRoleList")
    public Tip userRoleList(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                     @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req){
        Page<StaffDict> page=new Page<>(pageNo,pageSize);
        String roleId = req.getParameter("roleId");
        String username = req.getParameter("username");
        IPage<StaffDict> pageList = baseService.getUserByRoleId(page,roleId,username);
        return new SuccessTip(pageList);
    }

    @RequestMapping(value = "/queryUserRole",method = RequestMethod.GET)
    public Tip queryUserRole(@RequestParam(name = "userid")String userid){
        List<SysUserRole> userRoleList=sysUserRoleService.list(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId,userid));
        if(userRoleList==null||userRoleList.size()<=0){
            return new ErrorTip(302,"未找到用户相关角色信息");
        }
        return new SuccessTip(userRoleList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList()));
    }
    @RequestMapping(value = "/updatePassword",method = RequestMethod.PUT)
    public Tip changePassword(@RequestBody JSONObject json){
        String username=json.getString("username");
        String oldPassword=json.getString("oldpassword");
        String password=json.getString("password");
        String conformpassword=json.getString("confirmpassword");
        StaffDict user = baseService.getOne(new LambdaQueryWrapper<StaffDict>().eq(StaffDict::getStaffNo, username));
        if(user==null){
            return new ErrorTip(302,"用户不存在");
        }
        boolean result = baseService.resetPassword(username, oldPassword, password, conformpassword);
        if(result){
            return new SuccessTip("操作成功");
        }else {
            return new ErrorTip(302,"操作失败");
        }
    }
}

